# An utility module. It contains some useful methods to handle files.
module RedBook::Utils
	
	# Load a YAML file into memory. If _klass_ is @Array@, the <tt>YAML.load_documents</tt> method
	# will be called, otherwise the YAML file will be loaded using <tt>YAML.load_file</tt>.
	def load_yaml_file(klass, file)
		data = nil
		if file.exists? then
			begin
				if klass == Array then
					data = []
					YAML.load_documents(File.open(file)) do |d|
						data << d
					end
				else
					data = YAML.load_file(file)
				end
			rescue Exception => e
				if e.is_a? ArgumentError then
					raise GenericError, "Invalid YAML file: \"#{file}\""
				end
				raise GenericError, "Invalid YAML file: \"#{file}\""
			end
		else
			raise GenericError, "File \"#{file}\" not found."
		end
		data
	end
	
	# Create a new file if it doesn't already exist.
	def create_file(file)
		unless File.exist?(file)
			wrote_file('', file)
		else
			raise GenericError, "File #{file} already exists."
		end
	end

	# Write _contents_ to a _file_, according to the specified _mode_.
	def write_file(contents, file, mode='w+')
		File.open(file, mode) do |f|
			f.puts contents
		end
	end
	
	# Move the file _src_ to the _dest_ folder
	def move_file(src, dest, folder_name="folder")
		if File.exist?(dest) then
			File.move(src, dest)
		else
			raise GenericError, "#{folder_name.titleize} does not exist."
		end
	end

end
